package com.example.rootexplorer;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	ProgressDialog pDialog;
	ListView lvListItem;
	ListView lvListFTPItem;
	Button btnRoot;
//	Button btnParent;
	Button btnFTP;
	Button btnAction;
	Button btnExit;
	
	// Local
	ImageButton ibtnParentLocal;
	ImageButton ibtnAddFolderLocal;
	ImageButton ibtnRenameLocal;
	ImageButton ibtnDeleteLocal;
	ImageButton ibtnUpload;
//	int parentLevelLocal = 0;
	// Server
	ImageButton ibtnParentServer;
	ImageButton ibtnAddFolderServer;
	ImageButton ibtnRenameServer;
	ImageButton ibtnDeleteServer;
	ImageButton ibtnDownload;
	int parentLevelServer = 0;
	
	// Rename Dialog
	EditText rename;
	Button btnOk;
	Dialog renameDialog;
	
	// create directory Dialog
	EditText newDirectory;
	Button btnDirectoryOk;
	Dialog createDirectoryDialog;
	
	// message delete confirm
	TextView deleteConfirm;
	Button btnDeleteConfirmOk;
	Button btnDeleteConfirmCancel;
	Dialog deleteConfirmDialog;
	
	File file;
//	File parentFile = null;
	File sdcardRoot;
	File [] listFiles;
	Toast toast;
	File fileRoot = null;
	
	final Context context = this;
	Dialog ftpConnectPopup = null;
	
	boolean rootFlg = false;
	boolean isProVersion = false;
	boolean isAction = false;
	
	EditText ftpServer;
	EditText ftpUserName;
	EditText ftpPassword;
	
	FTPFile [] listFTPFile;
	FTPFile ftpFile;
	FTPFile ftpRootFile;
	
	FTPClient clientFTP = new FTPClient();
//	FilenameFilter filenameFilter;
	
	public boolean loginSuccess = false;
	public boolean isConnected = false;
	
	DecimalFormat decimalFormat;
	
	public List<File> listFileRecursive = new ArrayList<File>(); 
	public long totalFileSizeRecursive = 0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        decimalFormat = new DecimalFormat("#.##");
        lvListItem = (ListView) findViewById(R.id.lvListItem);
        lvListFTPItem = (ListView) findViewById(R.id.lvListFTPItem);
        btnRoot = (Button) findViewById(R.id.btnRoot);
        btnFTP = (Button) findViewById(R.id.btnFTP);
        btnAction = (Button) findViewById(R.id.btnAction);
        btnExit = (Button) findViewById(R.id.btnExit);
        
        // Local
        ibtnUpload = (ImageButton) findViewById(R.id.ibtnUpload);
        ibtnUpload.setEnabled(false);
        ibtnAddFolderLocal = (ImageButton) findViewById(R.id.ibtnAddFolderLocal);
        ibtnDeleteLocal = (ImageButton) findViewById(R.id.ibtnDeleteLocal);
        ibtnDeleteLocal.setEnabled(false);
        ibtnRenameLocal = (ImageButton) findViewById(R.id.ibtnRenameLocal);
        ibtnRenameLocal.setEnabled(false);
        ibtnParentLocal = (ImageButton) findViewById(R.id.ibtnParentLocal);
        ibtnParentLocal.setEnabled(false);
        // Server
        ibtnDownload = (ImageButton) findViewById(R.id.ibtnDownload);
        ibtnDownload.setEnabled(false);
        ibtnParentServer = (ImageButton) findViewById(R.id.ibtnParentServer);
        
        // rename dialog
        renameDialog = new Dialog(context, R.style.DialogTheme);
        renameDialog.setContentView(R.layout.popup_rename);
        renameDialog.setTitle("Rename file or directory");
        rename = (EditText) renameDialog.findViewById(R.id.rename);
        btnOk = (Button) renameDialog.findViewById(R.id.btnOk);
        
        // create directory dialog
        createDirectoryDialog = new Dialog(context, R.style.DialogTheme);
        createDirectoryDialog.setContentView(R.layout.popup_create_directory);
        createDirectoryDialog.setTitle("Create directory");
        newDirectory = (EditText) createDirectoryDialog.findViewById(R.id.newDirectory);
        btnDirectoryOk = (Button) createDirectoryDialog.findViewById(R.id.btnDirectoryOk);
        // filter file: don't show hidden file
//        filenameFilter = new FilenameFilter() {
//			
//			@Override
//			public boolean accept(File dir, String filename) {
//				if(filename!= null && filename.length() > 1 && ".".equals(filename.substring(0, 1))) return false;
//				return true;
//			}
//		};
        
        // show message dialog confirm
        deleteConfirmDialog = new Dialog(context, R.style.DialogTheme);
        deleteConfirmDialog.setContentView(R.layout.popup_delete_confirm);
        deleteConfirmDialog.setTitle("Alert Confirm");
        deleteConfirm = (TextView) deleteConfirmDialog.findViewById(R.id.deleteConfirm);
        btnDeleteConfirmOk = (Button) deleteConfirmDialog.findViewById(R.id.btnDeleteConfirmOk);
        btnDeleteConfirmCancel = (Button) deleteConfirmDialog.findViewById(R.id.btnDeleteConfirmCancel);
        
        file = Environment.getExternalStorageDirectory();
        sdcardRoot = Environment.getExternalStorageDirectory();
//        listFiles = file.listFiles(filenameFilter);
        listFiles = fileFilter(file.listFiles());
        
        lvListItem.setAdapter(new ListItemAdapter(listFiles));
        
        
        
        // Click list file
        lvListItem.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
        		ibtnDownload.setEnabled(false);
//        		File temp = file.getParentFile();
//        		if(temp == null || (!isProVersion && sdcardRoot.equals(file))) {
        		File temp = (File)parent.getItemAtPosition(position);
//        		} else {
//        			if(position > 0) {
//            			temp = (File)parent.getItemAtPosition(position-1);
//            		}
//        		}
//        		if(temp != null && isProVersion) {
//        			if(position > 0) {
//            			temp = (File)parent.getItemAtPosition(position-1);
//            		}
//        		} else {
//        			temp = (File)parent.getItemAtPosition(position);
//        			
//        		}
        		ibtnRenameLocal.setEnabled(isAction);
    			ibtnDeleteLocal.setEnabled(isAction);
        		if(isAction) {
        			ibtnRenameLocal.setImageResource(R.drawable.rename);
        			ibtnDeleteLocal.setImageResource(R.drawable.delete);
        		} else {
        			ibtnRenameLocal.setImageResource(R.drawable.rename_hide);
        			ibtnDeleteLocal.setImageResource(R.drawable.delete_hide);
        		}
        		
        		if(temp.isDirectory()) {
        			ibtnUpload.setEnabled(false);
        			file = temp;
        			if(isAction) return;
//	        		btnParent.setEnabled(true);
	        		listFiles = fileFilter(file.listFiles());
	        		if(listFiles.length == 0) {
	        			showMessage("No file or folder!");
	        		}
	        		lvListItem.setAdapter(new ListItemAdapter(listFiles));
//	        		parentLevelLocal++;
	        		ibtnParentLocal.setEnabled(true);
	        		ibtnParentLocal.setImageResource(R.drawable.up);
        		} else 
        		{
        			//showMessage("No support!");
        			ibtnUpload.setEnabled(loginSuccess);
        			file = temp;
        		}
        		
        	}
		});
        
        lvListFTPItem.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
        		ibtnUpload.setEnabled(false);
        		FTPFile temp = (FTPFile)parent.getItemAtPosition(position);
        		if(temp.isDirectory()) {
        			ftpFile = temp;
        			if(isAction) return;
        			// check parentLevel
        			parentLevelServer++;
        			
        			ibtnDownload.setEnabled(false);
        			ibtnParentServer.setEnabled(true);
        			try {
        				clientFTP.changeWorkingDirectory(temp.getName());
						listFTPFile = ftpFileFilter(clientFTP.listFiles());
						lvListFTPItem.setAdapter(new ListFTPItemAdapter(listFTPFile));
					} catch (IOException e) {
						e.printStackTrace();
					}
//        			listFTPFile = ftpFile.
        		} else {
        			//showMessage("No support!");
        			ftpFile = temp;
        			ibtnDownload.setEnabled(loginSuccess);
        		}
        	}
		});
        
        // Click Parent Button
//        btnParent.setOnClickListener(new View.OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				if(file.getParentFile() != null) {
//					file = file.getParentFile();
//					listFiles = file.listFiles();
//					lvListItem.setAdapter(new ListItemAdapter(listFiles));
//					if(sdcardRoot.equals(file) && !rootFlg) {
//						btnParent.setEnabled(false);
//					}
//				}
//				
//			}
//		});
        
        btnRoot.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(isProVersion) {
					if(fileRoot == null) {
						fileRoot = new File("/root");
						File [] listFileRoot = fileRoot.listFiles();
						if(listFileRoot != null && listFileRoot.length > 0) {
							rootFlg = true;
//							btnParent.setEnabled(true);
							btnRoot.setEnabled(false);
						} else {
							showMessage("System doesn't set root authorization yet!");
							fileRoot = null;
						}
					}
				} else {
					showMessage("Update to Pro version to use it!");
				}
			}
		});
        
        btnFTP.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				ftpConnectPopup = new Dialog(context, R.style.DialogTheme);
				ftpConnectPopup.setContentView(R.layout.popup_ftp_connect);
				ftpConnectPopup.setTitle("FTP Server Connect");
				ftpConnectPopup.show();
				
				ftpServer = (EditText) ftpConnectPopup.findViewById(R.id.ftpServer);
				ftpUserName = (EditText) ftpConnectPopup.findViewById(R.id.ftpUserName);
				ftpPassword = (EditText) ftpConnectPopup.findViewById(R.id.ftpPassword);
				
				Button btnLogin = (Button) ftpConnectPopup.findViewById(R.id.btnLogin);
				Button btnClose = (Button) ftpConnectPopup.findViewById(R.id.btnClose);
				
				btnLogin.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						FTPClientThread clientFTPThread = new FTPClientThread(ftpServer.getText().toString(), ftpUserName.getText().toString(), ftpPassword.getText().toString());
						clientFTPThread.execute();
					}
				});
				
				btnClose.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						ftpConnectPopup.dismiss();
					}
				});
			}
		});
        
        btnAction.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				isAction = (isAction != true);
				if(isAction) {
					btnAction.setText("UnAction");
					ibtnRenameLocal.setImageResource(R.drawable.rename);
        			ibtnDeleteLocal.setImageResource(R.drawable.delete);
				} else {
					btnAction.setText("Action");
					ibtnRenameLocal.setEnabled(false);
					ibtnDeleteLocal.setEnabled(false);
					ibtnRenameLocal.setImageResource(R.drawable.rename_hide);
        			ibtnDeleteLocal.setImageResource(R.drawable.delete_hide);
				}
			}
		});
        
        ibtnUpload.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//showMessage("Click upload");
				//client.storeFile(fileName, new FileInputStream(sendFile))
				try {
					if(!isFileExists(clientFTP.listNames(), file.getName())) {
						
						//
						FTPClientThread clientThread = new FTPClientThread(file);
						clientThread.execute();
					} else {
						showMessage("File is exist!");
					}
				} catch (Exception e) {
					Log.e("Click ibtnUpload", e.getCause().toString());
					e.printStackTrace();
				}
			}
		});
        
        ibtnDownload.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!isFileExists(file.list(), ftpFile.getName())) {
					FTPClientThread clientThread = new FTPClientThread(ftpFile);
					clientThread.execute();
				}else {
					showMessage("File is exist!");
				}
				
			}
		});
        
        btnExit.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				try {
					if(loginSuccess) clientFTP.logout();
					if(isConnected)	clientFTP.disconnect();
				} catch (Exception e) {
					Log.e("ClientFTP logout or disconnect error!", e.getMessage());
				}
				finish();
			}
		});
        
        ibtnParentServer.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try {
					
					if(parentLevelServer > 0) {
						if(clientFTP.changeToParentDirectory()) {
							listFTPFile = ftpFileFilter(clientFTP.listFiles());
							lvListFTPItem.setAdapter(new ListFTPItemAdapter(listFTPFile));
						}
						parentLevelServer--;
						if(parentLevelServer == 0) {
							ibtnParentServer.setEnabled(false);
						}
					} 
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
        
        ibtnDeleteLocal.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				listFileRecursive.add(file);
				findRecursiveFile(file);
				deleteConfirmDialog.show();
				if(totalFileSizeRecursive > 0 && file.isDirectory()) {
					deleteConfirm.setText("Total file size: " + getByteName(totalFileSizeRecursive));
				} else {
					deleteConfirm.setText("Do you want to delete: " + file.getName());
				}
				
				btnDeleteConfirmOk.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						deleteConfirmDialog.hide();
						ibtnDeleteLocal.setEnabled(false);
						ibtnRenameLocal.setEnabled(false);
						ibtnRenameLocal.setImageResource(R.drawable.rename_hide);
	        			ibtnDeleteLocal.setImageResource(R.drawable.delete_hide);
						ActionThread actionThread = new ActionThread(ActionThread.CALL_DELETE_FUNCTION);
						actionThread.execute();
						
					}
				});
				btnDeleteConfirmCancel.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						deleteConfirmDialog.hide();
					}
				});
			}
		});
        
        ibtnParentLocal.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
//				if(!sdcardRoot.equals(file.getParent())) {
					file = file.getParentFile();
					listFiles = fileFilter(file.listFiles());
	        		lvListItem.setAdapter(new ListItemAdapter(listFiles));
	        		if(sdcardRoot.equals(file)) {
	        			ibtnParentLocal.setEnabled(false);
	        			ibtnParentLocal.setImageResource(R.drawable.up_hide);
	        		}
//				}
			}
		});
        
        ibtnRenameLocal.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				renameDialog.show();
				rename.setText(file.getName());
				btnOk.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						File tmpFileParent = file.getParentFile();
						File tmpFile = new File(tmpFileParent.getPath() + File.separator + rename.getText().toString());
						if(file.renameTo(tmpFile)){
							file = tmpFileParent;
							listFiles = fileFilter(file.listFiles());
							lvListItem.setAdapter(new ListItemAdapter(listFiles));
						}
						renameDialog.hide();
						ibtnDeleteLocal.setEnabled(false);
						ibtnRenameLocal.setEnabled(false);
						ibtnRenameLocal.setImageResource(R.drawable.rename_hide);
		    			ibtnDeleteLocal.setImageResource(R.drawable.delete_hide);
					}
				});
			}
		});
        
        ibtnAddFolderLocal.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				createDirectoryDialog.show();
				newDirectory.setText("New Folder");
				btnDirectoryOk.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						File tmpParentFile;
						if(file.isDirectory()) {
							tmpParentFile = file;
						} else {
							tmpParentFile = file.getParentFile();
						}
						String tmpFileName = tmpParentFile.getPath() + File.separator + newDirectory.getText().toString();
						File tmpFile = new File(tmpFileName);
						if(tmpFile.exists() && tmpFile.isDirectory()) {
							showMessage("Directory is exist!");
						} else {
							if(tmpFile.mkdir()) {
								listFiles = fileFilter(tmpParentFile.listFiles());
								lvListItem.setAdapter(new ListItemAdapter(listFiles));
							}
							createDirectoryDialog.hide();
						}
					}
				});
				String newFileName = file.getParentFile().getPath() + File.separator + "New Folder";
				File tmpFile = new File(newFileName);
				if(tmpFile.exists()) {
					
				}
			}
		});
    }
    
//    /**
//     * delete all file
//     */
//    public void deleteFileRecursive() {
//    	//File tmpFile = file.getParentFile();
//    	file = file.getParentFile();
//    	File tmpFile = null;
//    	int size = listFileRecursive.size();
//    	for(int i = size -1; i > 0; i--){
//    		tmpFile = listFileRecursive.get(i);
//    		tmpFile.delete();
//    	}
//		// delete
//		//file.delete();
//		//file = tmpFile;
//		ibtnDeleteLocal.setEnabled(false);
//		ibtnUpload.setEnabled(false);
//		listFiles = fileFilter(file.listFiles());
//		if(listFiles.length == 0) {
//			showMessage("No file or folder!");
//		}
//		lvListItem.setAdapter(new ListItemAdapter(listFiles));
//    }
    
    public File getFile() {
    	return file;
    }
    
    public void refreshFTPServer() {
    	try {
    		listFTPFile = ftpFileFilter(clientFTP.listFiles());
    		lvListFTPItem.setAdapter(new ListFTPItemAdapter(listFTPFile));
		} catch (Exception e) {
			Log.e("refreshFTPServer", e.toString());
		}
    }
    
    public void getFTPFile(String srcName, String destPath, String destName) {
    	//File destFile = Environment.getExternalStorageDirectory();
    	BufferedOutputStream fos = null;
    	try {
			fos = new BufferedOutputStream(new FileOutputStream(destPath + "/" + destName));
			clientFTP.retrieveFile(srcName, fos);
		} catch (IOException e) {
			e.printStackTrace();
			Log.e("getFTPFile", e.toString());
		} finally {
			try {
				if(fos != null) fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
    
    /**
     * check file exists
     * @param listNames
     * @param name
     * @return
     */
    public boolean isFileExists(String [] listNames, String name) {
    	boolean flg = false;
    	if(listNames != null && listNames.length > 0) {
    		for(int i = 0; i < listNames.length; i++) {
    			if(name.equals(listNames[i])) {
    				flg = true;
    				break;
    			}
    		}
    	}
    	return flg;
    }
    
    /**
     * 
     * @param list
     * @return
     */
    public File [] fileFilter(File[] list) {
    	if(list == null) return null;
    	List<File> lstFile = new ArrayList<File>();
    	List<File> lstFolder = new ArrayList<File>();
    	for(File tmpFile:list) {
    		// except hidden file
    		if(!".".equals(tmpFile.getName().substring(0, 1))) {
    			if(tmpFile.isDirectory()) {
        			lstFolder.add(tmpFile);
        		} else {
        			lstFile.add(tmpFile);
        		}
    		}
    	}
    	int sizeFile = lstFile.size();
    	int sizeFolder = lstFolder.size();
    	File [] lstTotalFile = new File [sizeFile + sizeFolder];
    	int i;
    	if(sizeFolder > 0) {
    		File [] lstTmFolder = new File[sizeFolder];
    		// convert array to list
    		for(i = 0; i < sizeFolder; i++) {
    			lstTmFolder[i] = lstFolder.get(i);
    		}
    		lstTmFolder = sortFileAsc(lstTmFolder);
    		// add to total list
    		for(i = 0; i < sizeFolder; i++) {
    			lstTotalFile [i] = lstTmFolder[i];
    		}
    	}
    	
    	
    	if(sizeFile > 0) {
    		File [] lstTmpFile = new File[sizeFile];
    		// convert array list to list
    		for(i = 0; i < sizeFile; i++) {
    			lstTmpFile[i] = lstFile.get(i);
    		}
    		// sort
    		lstTmpFile = sortFileAsc(lstTmpFile);
    		// add to total list
    		for(i = 0; i < sizeFile; i++) {
    			lstTotalFile [i + sizeFolder] = lstTmpFile[i];
    		}
    	}
    	
    	return lstTotalFile;
    }
    
    /**
     * sort file ascending
     * @param list
     * @return
     */
    private File [] sortFileAsc(File[] list) {
    	int size = list.length;
    	File tmpFile = null;
    	for(int i = 0; i < size - 1; i++) {
    		for(int j = i+1; j < size; j++) {
    			if(list[i].getName().toLowerCase().compareTo(list[j].getName().toLowerCase()) > 0) {
    				tmpFile = list[i];
    				list[i] = list[j];
    				list[j] = tmpFile;
    			}
    		}
    	}
    	return list;
    }
    
    /**
     * sort file ascending
     * @param list
     * @return
     */
    private FTPFile [] sortFileAsc(FTPFile[] list) {
    	int size = list.length;
    	FTPFile tmpFile = null;
    	for(int i = 0; i < size - 1; i++) {
    		for(int j = i+1; j < size; j++) {
    			if(list[i].getName().toLowerCase().compareTo(list[j].getName().toLowerCase()) > 0) {
    				tmpFile = list[i];
    				list[i] = list[j];
    				list[j] = tmpFile;
    			}
    		}
    	}
    	return list;
    }
    
    /**
     * filter FTPFile
     * @param list
     * @return
     */
    public FTPFile [] ftpFileFilter(FTPFile [] list) {
    	if(list == null) return null;
    	List<FTPFile> lstFTPFile = new ArrayList<FTPFile>();
    	List<FTPFile> lstFTPFolder = new ArrayList<FTPFile>();
    	for(FTPFile tmpFTPFile:list) {
    		if(!".".equals(tmpFTPFile.getName().substring(0, 1))) {
    			if(tmpFTPFile.isDirectory()) {
    				lstFTPFolder.add(tmpFTPFile);
    			} else {
    				lstFTPFile.add(tmpFTPFile);
    			}
    		}
    	}
    	int sizeFile = lstFTPFile.size();
    	int sizeFolder = lstFTPFolder.size();
    	FTPFile [] lstTotalFile = new FTPFile[sizeFile + sizeFolder];
    	int i;
    	if(sizeFolder > 0) {
    		FTPFile [] lstTmFolder = new FTPFile[sizeFolder];
    		// convert array to list
    		for(i = 0; i < sizeFolder; i++) {
    			lstTmFolder[i] = lstFTPFolder.get(i);
    		}
    		lstTmFolder = sortFileAsc(lstTmFolder);
    		// add to total list
    		for(i = 0; i < sizeFolder; i++) {
    			lstTotalFile [i] = lstTmFolder[i];
    		}
    	}
    	
    	if(sizeFile > 0) {
    		FTPFile [] lstTmpFile = new FTPFile[sizeFile];
    		// convert array list to list
    		for(i = 0; i < sizeFile; i++) {
    			lstTmpFile[i] = lstFTPFile.get(i);
    		}
    		// sort
    		lstTmpFile = sortFileAsc(lstTmpFile);
    		// add to total list
    		for(i = 0; i < sizeFile; i++) {
    			lstTotalFile [i + sizeFolder] = lstTmpFile[i];
    		}
    	}
    	
    	return lstTotalFile;
    }
    
    public void showMessage(String message) {
		toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
		toast.show();
    }
    
    public void dismissPopupFTPConnect() {
    	if(ftpConnectPopup != null) {
			ftpConnectPopup.dismiss();
		}
    }
    
    public String getByteName(long fileLength) {
    	String byteName = "";
    	if((fileLength / 1000000000) > 0) {
    		byteName = decimalFormat.format((double)fileLength/ (1024*1024*1024)) + " Gb";
    	} else if((fileLength / 1000000) > 0) {
    		byteName = decimalFormat.format((double)fileLength/ (1024*1024)) + " Mb";
    	} else if((fileLength / 1000) > 0) {
    		byteName = decimalFormat.format((double)fileLength/ (1024)) + " Kb";
    	} else {
    		byteName = fileLength + " B";
    	}
    	return byteName;
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    /**
     * find related file
     * @param File
     */
    public void findRecursiveFile(File tempFile) {
    	if(tempFile.isFile()) {
    		totalFileSizeRecursive += tempFile.length();
    	} else {
    		
    		File [] listTempFile = tempFile.listFiles();
        	int size = listTempFile.length;
        	if (size > 0) {
        		File tmp = null;
    			for(int i = 0; i < size; i++) {
    				tmp = listTempFile[i];
    				listFileRecursive.add(tmp);
    				if(tmp.isDirectory()) {
    					findRecursiveFile(tmp);
    				} else {
    					totalFileSizeRecursive += tmp.length();
    				}
    			}
    		}
    	}
    }
    
    class ListItemAdapter extends BaseAdapter {

    	private File [] listItems;
    	public ListItemAdapter(File [] listFiles) {
    		super();
    		this.listItems = listFiles;
    	}
		public int getCount() {
//			if(getFile().getParent() == null || (!isProVersion && sdcardRoot.equals(getFile()))) {
				if(listItems == null)return 0;
				return listItems.length;
//			} else {
//				if(listItems == null)return 1;
//				return listItems.length + 1;
//			}
			
		}

		public Object getItem(int pos) {
			return listItems[pos];
		}

		public long getItemId(int arg0) {
			return 0;
		}

		public View getView(int pos, View view, ViewGroup parent) {
			try {
				LayoutInflater inflater = getLayoutInflater();
				view = inflater.inflate(R.layout.lv_list_item_row, parent, false);
				TextView tvItemRow = (TextView) view.findViewById(R.id.tvItemRow);
				ImageView ivItemRow = (ImageView) view.findViewById(R.id.ivItemRow);
				TextView tvItemRowInfo = (TextView) view.findViewById(R.id.tvItemRowInfo);
//				String fileName = "..";
				File file = null;
//				if(getFile().getParent() == null || (!isProVersion && sdcardRoot.equals(getFile()))) {
				file = listItems[pos];
				String fileName = file.getName();
				if(file.isFile()) {
					ivItemRow.setImageResource(R.drawable.file);
					tvItemRowInfo.setHint(getByteName(file.length()));
				} else {
					ivItemRow.setImageResource(R.drawable.folder);
				}
//				} else {
//					if(pos > 0) {
//						file = listItems[pos - 1];
//						fileName = file.getName();
//					}
//					if(pos > 0 && file.isFile()) {
//						ivItemRow.setImageResource(R.drawable.file);
//						tvItemRowInfo.setHint(getByteName(file.length()));
//					} else {
//						ivItemRow.setImageResource(R.drawable.folder);
//					}
//				}
				
				tvItemRow.setText(fileName);
				
			} catch (Exception e) {
				Log.e("ListItemAdapter.getView(" + pos + ", " + view != null ? view.toString() : "null" + parent != null ? parent.toString() : "null", e.getMessage());
			}
			return view;
		}

    }
    
    class ListFTPItemAdapter extends BaseAdapter {

    	private FTPFile [] listFTPItems;
    	public ListFTPItemAdapter(FTPFile [] listFTPFiles) {
    		super();
    		this.listFTPItems = listFTPFiles;
    	}
		public int getCount() {
//			if(getFile().getParent() == null || (!isProVersion && sdcardRoot.equals(getFile()))) {
//				if(listItems == null)return 0;
//				return listItems.length;
//			} else {
//				if(listItems == null)return 1;
//				return listItems.length + 1;
//			}
//			if(ftpFile.)
			if(listFTPItems == null)return 0;
			return listFTPItems.length;
		}

		public Object getItem(int pos) {
			return listFTPItems[pos];
		}

		public long getItemId(int arg0) {
			return 0;
		}

		public View getView(int pos, View view, ViewGroup parent) {
			try {
				LayoutInflater inflater = getLayoutInflater();
				view = inflater.inflate(R.layout.lv_list_item_row, parent, false);
				TextView tvItemRow = (TextView) view.findViewById(R.id.tvItemRow);
				TextView tvItemRowInfo = (TextView) view.findViewById(R.id.tvItemRowInfo);
				FTPFile file = listFTPItems[pos];
				
				String fileName = file.getName();
				tvItemRow.setText(fileName);
				ImageView ivItemRow = (ImageView) view.findViewById(R.id.ivItemRow);
				if(file.isFile()) {
					ivItemRow.setImageResource(R.drawable.file);
					tvItemRowInfo.setHint(getByteName(file.getSize()));
				} else {
					ivItemRow.setImageResource(R.drawable.folder);
				}
				
			} catch (Exception e) {
				Log.e("ListItemAdapter.getView(" + pos + ", " + view != null ? view.toString() : "null" + parent != null ? parent.toString() : "null", e.getMessage());
			}
			return view;
		}

    }

    class FTPClientThread extends AsyncTask<String, Integer, String>{

		private File sendFile = null;
		private FTPFile retrieveFTPFile = null;
		
		private String ftpServer;
		private String userName;
		private String password;
		
		public FTPClientThread(File file)
		{
			super();
			sendFile = file;
		}
		
		public FTPClientThread(FTPFile retrieveFTPFile)
		{
			super();
			this.retrieveFTPFile = retrieveFTPFile;
		}
		
		public FTPClientThread(String ftpServer, String userName, String password) {
			this.ftpServer = ftpServer;
			this.userName = userName;
			this.password = password;
		}
		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(context);
			pDialog.setMessage("Please wait a few minutes...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
//			pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//			pDialog.setProgress(0);
//			pDialog.setMax(100);
			pDialog.show();
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
//			pDialog.setProgress(values[0]);
		}
		
		@Override
		protected String doInBackground(String... params) {
			
			try {
				//client.connect("ftp://dounets.com/",21);
				//client.connect(InetAddress.getByName("113.161.74.175"));
				//client.login("administrator", "ftp1234");
				//client.changeWorkingDirectory("/SI_Automation_SMA/Son");
				//String url = "ftp.freevnn.com/htdocs/movies";
//				String url = "http://phucbui.freevnn.com/movies/";
//				client.connect("ftp.freevnn.com");
//				client.login("freev_11547291", "Abcd1234");
//				client.changeWorkingDirectory("/htdocs/movies");
//				client.setFileType(FTP.BINARY_FILE_TYPE);
//				client.enterLocalPassiveMode();
//				clientFTP.setConnectTimeout(5000);
				if(sendFile == null && retrieveFTPFile == null) {
					clientFTP.connect(ftpServer);
					if(clientFTP.isConnected()) {
						isConnected = true;
						if(clientFTP.login(userName, password)) {
							clientFTP.setFileType(FTP.BINARY_FILE_TYPE);
							clientFTP.enterLocalPassiveMode();
							//listFTPFile = ftpFileFilter(clientFTP.listFiles());
							loginSuccess = true;
						} 
					} 
				} else if(sendFile != null) {
					clientFTP.storeFile(sendFile.getName(), new FileInputStream(sendFile));
					//
				} else if(retrieveFTPFile != null) {
					String destPath = "/";
					if(getFile().getParent() != null) {
//						if(sdcardRoot.equals(getFile())) {
//							
//						}
						destPath = getFile().getPath();
					}
					getFTPFile(ftpFile.getName(), destPath, ftpFile.getName());
				}
				
				
//				if(sendFile != null)
//				{
//					String fileName = sendFile.getName();
//					fileName = System.currentTimeMillis() + "_"+  fileName;
//					
//					client.storeFile(fileName, new FileInputStream(sendFile));
//					
//					
//				}
				
				//clientFTP.logout();
				//clientFTP.disconnect();
			} catch (SocketException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return "Success";
		}
		
		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			pDialog.dismiss();
			// dismiss the dialog after getting all products
			if(isConnected) {
				if(loginSuccess) {
					try {
						listFTPFile = ftpFileFilter(clientFTP.listFiles());
						lvListFTPItem.setAdapter(new ListFTPItemAdapter(listFTPFile));
						listFiles = fileFilter(file.listFiles());
		        		lvListItem.setAdapter(new ListItemAdapter(listFiles));
						
						dismissPopupFTPConnect();
						
						ibtnParentServer.setVisibility(View.VISIBLE);
						ibtnDownload.setVisibility(View.VISIBLE);
						ibtnUpload.setVisibility(View.VISIBLE);
						ibtnUpload.setEnabled(false);
						ibtnDownload.setEnabled(false);
						ibtnParentServer.setEnabled(false);
						//if connect ftp server success, disable FTP button
						//btnFTP.setEnabled(false);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					showMessage("Invalid username or password!");
				}
			} else {
				showMessage("Invalid ftp server!");
			}
		}
    }
    
    class ActionThread extends AsyncTask<String, Integer, String>{

		public static final String CALL_DELETE_FUNCTION = "1"; 
		private String action = "";
		
		public ActionThread(String action)
		{
			super();
			this.action = action;
		}
		
		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(context);
			pDialog.setMessage("Please wait a few minutes...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
//			pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//			pDialog.setProgress(0);
//			pDialog.setMax(100);
			pDialog.show();
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
//			pDialog.setProgress(values[0]);
		}
		
		@Override
		protected String doInBackground(String... params) {
			
			try {
				if(CALL_DELETE_FUNCTION.equals(action)) {
					file = file.getParentFile();
			    	File tmpFile = null;
			    	int size = listFileRecursive.size();
			    	for(int i = size -1; i >= 0; i--){
			    		tmpFile = listFileRecursive.get(i);
			    		tmpFile.delete();
			    	}
					// delete
					//file.delete();
					//file = tmpFile;
					
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return "Success";
		}
		
		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			pDialog.dismiss();
			if(CALL_DELETE_FUNCTION.equals(action)) {
				ibtnDeleteLocal.setEnabled(false);
				ibtnRenameLocal.setEnabled(false);
				ibtnRenameLocal.setImageResource(R.drawable.rename_hide);
    			ibtnDeleteLocal.setImageResource(R.drawable.delete_hide);
				ibtnUpload.setEnabled(false);
				listFiles = fileFilter(file.listFiles());
				if(listFiles.length == 0) {
					showMessage("No file or folder!");
				}
				lvListItem.setAdapter(new ListItemAdapter(listFiles));
			}
		}
    }
    
}
